﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.IService;
using System.Web;
using HPIT.RentHouse.Service.Entites;
using System.Data.Entity.Migrations;
using HPIT.RentHouse.Common;

namespace HPIT.RentHouse.Service
{
    public class AdminUsersService : IAdminUsersService
    {
        MyDbContext _dbContext;
        public AdminUsersService(MyDbContext dbContext)
        { 
            this._dbContext = dbContext;
         }

        public List<AdminUserDTO> GetList()
        {
            return _dbContext.T_AdminUsers.Select(e => new AdminUserDTO
            {
                Id = e.Id,
                Name = e.Name,
                CityId = e.CityId == null ? 0 : (long)e.CityId,
                Email = e.Email,
                LoginErrorTimes = e.LoginErrorTimes,
                PhoneNum = e.PhoneNum,
                CityName = e.T_Cities.Name
            }).ToList(); 
            
        }

        /// <summary>
        ///新增账户进数据库，把密码进行加密
        /// </summary>
        /// <param name="loginDTO"></param>
        /// <returns></returns>
        public int Add(LoginDTO loginDTO) {
            T_Login t_Login = new T_Login();
            //已经加密后的密码
            t_Login.passwordHash = loginDTO.Password;
            t_Login.salt = loginDTO.Salt;
            t_Login.phoneNum = loginDTO.PhoneNum;
            _dbContext.T_Login.AddOrUpdate(t_Login);
            return  _dbContext.SaveChanges();
        }


        public  Boolean Login(LoginDTO loginDTO) {
            T_Login t_Login = _dbContext.T_Login.Where(s => s.phoneNum.Equals(loginDTO.PhoneNum)).First();
            return t_Login.passwordHash.Equals(CommonHelper.CalcMD5(loginDTO.PhoneNum + t_Login.salt));
        }

    }
}
